package newFeatureOfJava8;

import java.util.Optional;

/**
 * @author 26029
 * @date 2025/4/21
 * @description
 */
public class LearnOptional {
    public static void main(String[] args) {
        Optional<String> optOrNull = Optional.of("abcdefg");
        System.out.println(optOrNull.isPresent());
        System.out.println(optOrNull.isEmpty());
        optOrNull.ifPresent(s -> System.out.println(s.toUpperCase()));
        // 设置（获取）默认值
        String nullName = null;
        String name1 = Optional.ofNullable(nullName).orElse("沉默王二");
        String name2 = Optional.ofNullable(nullName).orElseGet(()->"沉默王二");
        System.out.println(name1); // 输出：沉默王二
        System.out.println(name2); // 输出：沉默王二

        String name = "CHR";
        String name3 = Optional.ofNullable(name).orElse(getDefaultName());
        System.out.println(name3); // orElse执行了getDefaultName方法
        String name4 = Optional.ofNullable(name).orElseGet(LearnOptional::getDefaultName);
        System.out.println(name4); // orElseGet没执行getDefaultName方法
    }

    public static String getDefaultName() {
        System.out.println("获取了默认name");
        return "default";
    }
}
